package com.zhiwang.planet.ui

import android.Manifest
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Bundle
import android.os.PersistableBundle
import android.os.Process
import android.os.SystemClock
import android.provider.Settings
import android.text.Html
import android.text.SpannableString
import android.text.Spanned
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.Menu
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import androidx.annotation.NonNull
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import androidx.lifecycle.Observer
import com.airbnb.lottie.LottieAnimationView
import com.bytedance.sdk.openadsdk.AdSlot
import com.bytedance.sdk.openadsdk.TTAdNative
import com.bytedance.sdk.openadsdk.TTAdSdk
import com.bytedance.sdk.openadsdk.TTRewardVideoAd
import com.cmcm.cmgame.CmGameSdk
import com.cmcm.cmgame.IGamePlayTimeCallback
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.tencent.bugly.crashreport.CrashReport
import com.zhiwang.planet.App
import com.zhiwang.planet.BuildConfig
import com.zhiwang.planet.R
import com.zhiwang.planet.di.ComponentProvider
import com.zhiwang.planet.di.component.DaggerMainComponent
import com.zhiwang.planet.di.component.MainComponent
import com.zhiwang.planet.di.module.AccountModule
import com.zhiwang.planet.di.module.AutoDisposeModule
import com.zhiwang.planet.event.*
import com.zhiwang.planet.mvp.p.CheckUpdatePresenter
import com.zhiwang.planet.mvp.p.EntertainPresenter
import com.zhiwang.planet.mvp.p.SdkPresenter
import com.zhiwang.planet.mvp.p.UserPresenter
import com.zhiwang.planet.mvp.v.ApkUpdateView
import com.zhiwang.planet.mvvm.model.entity.main.ImportantNotice
import com.zhiwang.planet.mvvm.model.entity.main.UpdateCheck
import com.zhiwang.planet.mvvm.model.entity.main.VideoClipTaskResult
import com.zhiwang.planet.mvvm.viewmodel.ShareViewModel
import com.zhiwang.planet.mvvm.viewmodel.main.MainViewModel
import com.zhiwang.planet.mvvm.viewmodel.main.sharedViewModels
import com.zhiwang.planet.service.DownLoadService
import com.zhiwang.planet.ui.entertain.EntertainFragmentV3
import com.zhiwang.planet.ui.interf.UiProgress
import com.zhiwang.planet.ui.main.*
import com.zhiwang.planet.ui.main.v2.MoneyFragmentV2
import com.zhiwang.planet.util.*
import com.zhiwang.planet.widget.AdVideoDialog
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.play_time_dialog.view.*
import kotlinx.android.synthetic.main.promotion_activity_layout.view.*
import kotlinx.android.synthetic.main.upgrade_dialog_layout.*
import kotlinx.android.synthetic.main.upgrade_dialog_layout.view.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*
import javax.inject.Inject

class MainActivity : BaseActivity(), ComponentProvider<MainComponent>, FragmentChangeListener, ApkUpdateView, IGamePlayTimeCallback, UiProgress {

    //弃用，从后台切回前台，mainComponent为空
    override fun getComponent(): MainComponent {
        return mainComponent
    }

    @Inject
    lateinit var mainViewModel: MainViewModel

    lateinit var mainComponent: MainComponent

    @Inject
    lateinit var updatePresenter: CheckUpdatePresenter

    @Inject
    lateinit var entertainPresenter: EntertainPresenter

    @Inject
    lateinit var presenter: SdkPresenter

    @Inject
    lateinit var userPresenter: UserPresenter

    var isVisibleNow = true

    var tmpIgnoreVersion: Int = Int.MIN_VALUE

    var videoCompleted = false

    lateinit var adVideoSlot: AdSlot

    lateinit var ttAdNative: TTAdNative

    var promotionDialog: Dialog? = null

    var gamePromotionDialog: Dialog? = null

    var doubleDialogShown = false

    val shareViewModel by sharedViewModels<ShareViewModel>()
    val TAG = "MainActivity"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mainComponent = DaggerMainComponent.builder()
                .appComponent((application as App).appComponent)
                .accountModule(AccountModule(this))
                .autoDisposeModule(AutoDisposeModule(this))
                .build()
        mainComponent.inject(this)
        updatePresenter.apkUpdateView = this
        setContentView(R.layout.activity_main)
        flycoTabLayout.setDefaultTabData(
                arrayListOf(
                        Tab.of("首页", R.drawable.xg_tab_main, R.drawable.xg_tab_main_nor),
                        Tab.of("赚钱", R.drawable.xg_money, R.drawable.xg_money_nor),
                        Tab.of("邀请", R.drawable.xg_invite, R.drawable.xg_invite_nor),
                        Tab.of("我的", R.drawable.xg_my, R.drawable.xg_my_nor)
                ),
                supportFragmentManager,
                R.id.fragment_container,
                arrayListOf(
                        MainFragment(),
                        MoneyFragmentV2(),
                        EmptyFragment(),
                        MyFragment()
                ))
        if (savedInstanceState != null) {
            flycoTabLayout.currentTab = savedInstanceState.getInt("flycoTabIndex", 0)
        } else
            flycoTabLayout.currentTab = 0
        EventBus.getDefault().register(this)
        flycoTabLayout.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {

                if (!TokenManager.isLoginValid() && position != 0) {
                    flycoTabLayout.currentTab = 0
                    onAuthExpired()
                    return
                }

                if (position == 2) {
                    WebViewActivity.load(this@MainActivity, Store.URL_LOSER_INVITE)
                    changedTab = 0
                } else
                    shareViewModel.mainTabActive.value = flycoTabLayout.currentTab == 0

                updateStatusBar(0)
            }

            override fun onTabReselect(position: Int) {
                updateStatusBar(0)
            }

        })
        presenter.getPceggPageUrl()
//        presenter.getServiceQQ()
        if (TokenManager.isFirstTimeInstall()) showPrivacyDialog()
        TokenManager.install()
        presenter.reportAppLaunch(ChannelUtil.getChannel(this), AppHelper.getDeviceIdWithoutGuarantee(this))
        //每次进入应用都设置一下异常上报的 userid
        CrashReport.setUserId(TokenManager.webviewHeaderUserid())

        val width = resources.displayMetrics.widthPixels
        val height = resources.displayMetrics.heightPixels

        adVideoSlot = AdSlot.Builder()
                .setCodeId("931608653")
                .setSupportDeepLink(true)
                .setImageAcceptedSize(width, height)
                .build()
        ttAdNative = TTAdSdk.getAdManager().createAdNative(this)


        shareViewModel.messageCount.observe(this, Observer {
            flycoTabLayout.showMsg(0, it)
        })

        updatePresenter.getImportantNotice(::showNotice)


        shareViewModel.error.observe(this, Observer(this::onError))

        val deadLine = Calendar.getInstance().also {
            it.set(Calendar.YEAR, 2020)
            it.set(Calendar.MONTH, 7)
            it.set(Calendar.DAY_OF_MONTH, 21)
            it.set(Calendar.HOUR_OF_DAY, 6)
            it.set(Calendar.MINUTE, 0)
            it.set(Calendar.SECOND, 0)
        }

        doubleDialogShown = savedInstanceState?.getBoolean("doubleShown") ?: false

        if (Calendar.getInstance().before(deadLine) && doubleDialogShown.not())
            showDoubleDialog()


        qBister()
        qIdenticalBister()
        updateStatusBar(0)
    }

    private fun updateStatusBar(position: Int) {
        Utils.setStatusTextColor(true, this@MainActivity)

    }

    private fun showDoubleDialog() {

        val root = layoutInflater.inflate(R.layout.promotion_activity_layout, null)

        promotionDialog = AlertDialog.Builder(this)
                .setView(root)
                .create()
        promotionDialog?.show()

        root.promotion_img.setOnClickListener {
            WebViewActivity.load(this, Store.Promotion)
        }

        root.promotion_close.setOnClickListener { promotionDialog?.dismiss();showDouble2Dialog() }
        promotionDialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))

    }


    private fun showDouble2Dialog() {
        val root2 = layoutInflater.inflate(R.layout.promotion_activity_layout, null)

        root2.promotion_img.setImageResource(R.drawable.pic)

        gamePromotionDialog = AlertDialog.Builder(this)
                .setView(root2)
                .create()
        gamePromotionDialog?.show()

        gamePromotionDialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))

        root2.promotion_close.setOnClickListener {
            gamePromotionDialog?.dismiss()
        }

        root2.promotion_img.setOnClickListener {
            gamePromotionDialog?.dismiss()
            EventBus.getDefault().post(MobileEvent())
        }
        doubleDialogShown = true
    }


    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        return false
    }

    private fun showNotice(it: ImportantNotice?) {
        if (it?.show == 1) {


            val rootView = layoutInflater.inflate(R.layout.upgrade_dialog_layout, null)

            rootView.image.setImageResource(R.drawable.important_notice)
            rootView.upgrade_log.text = Html.fromHtml(it.content)
            rootView.upgrade_log.movementMethod = LinkMovementMethod.getInstance()
            rootView.title.text = it.title
            rootView.upgrade_now.text = "确定"

//            updateCheck.versionName?.apply {
//                rootView.upgrade_version.text = "版本$this"
//            }


            val dialog = AlertDialog.Builder(this)
                    .setView(rootView)
                    .setCancelable(false)
                    .create()
            rootView.upgrade_later.text = "取消"
            rootView.upgrade_later.setOnClickListener {
                dialog.dismiss()
            }
            rootView.upgrade_now.setOnClickListener {
                dialog.dismiss()
            }

            //transparent
            dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            dialog.show()

        }
    }

    private fun showPrivacyDialog() {

        val dialog = AlertDialog.Builder(this, R.style.MaterialDialogStyle)
                .setTitle(getString(R.string.title_service))
                .setMessage("请您务必甚深阅读，充分理解“服务协议”和“隐私政策”各条款，包括但不限于向你提供及时通讯，内容分享等服务" +
                        "并且需要手机你的设备信息，操作日志等。你可以登录后在个人页面右上角设置按钮进入设置中查看，也可在登录页面底部入口进入隐私协议。" +
                        "如你统一，请点击统开始接受我们的服务。")
                .setPositiveButton("同意") { inf, i ->
                    inf.dismiss()

                }
                .setNegativeButton("暂不使用") { inf, i ->
                    Process.killProcess(Process.myPid())

                }.create()
        dialog
                .show()


        val textView = dialog.findViewById<TextView>(android.R.id.message)!!

        val spanned = SpannableString("请您务必甚深阅读，充分理解“服务协议”和“隐私政策”各条款，包括但不限于向你提供及时通讯，内容分享等服务\n" +
                "    并且需要手机你的设备信息，操作日志等。你可以登录后在个人页面右上角设置按钮进入设置中查看，也可在登录页面底部入口进入《隐私协议》和《服务协议》。\n" +
                "    如您同意，请点击同意开始接受我们的服务。")
        spanned.setSpan(object : ClickableSpan() {

            override fun onClick(widget: View) {
                quickStartActivity(PrivacyActivity::class.java)
            }

        }, 115, 121, Spanned.SPAN_INCLUSIVE_INCLUSIVE)

        spanned.setSpan(object : ClickableSpan() {

            override fun onClick(widget: View) {
                WebViewActivity.load(this@MainActivity, Store.USER_AGREEMENT)
            }
        }, 122, 128, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
        textView.text = spanned
        textView.movementMethod = LinkMovementMethod.getInstance()
        textView.setTextIsSelectable(false)

    }


//    class Switcher constructor(val boomOrNot: Boolean):BmobObject()

    private var changedTab = -1
    private var stateSaved = false
    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putBoolean("doubleShown", doubleDialogShown)
        outState.putInt("flycoTabIndex", flycoTabLayout.currentTab)
        stateSaved = !stateSaved
    }

    override fun onRestoreInstanceState(savedInstanceState: Bundle?) {
        super.onRestoreInstanceState(savedInstanceState)
        stateSaved = false
    }

    /**
     * 由于里面涉及到fragment的切换，commit 可能在lossSate 的情况下发生异常退出，必须判断当前是否是saveSated状态
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onRequestTabChange(event: TabChangeEvent) {
        if (isVisibleNow) flycoTabLayout.currentTab = event.tabIndex
        else changedTab = event.tabIndex

        updateStatusBar(event.tabIndex)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onLogout(event: LogoutEvent) {
        changedTab = 0
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onAuthExp(e: AuthExpireEvent) {
        onAuthExpired()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onLogin(ev: LoginEvent) {
//        presenter.getPceggPageUrl()
////        presenter.getServiceQQ()
//        userPresenter.saveShareInfo(cacheDir)
        saveBister()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onTabChange(e: MobileEvent) {
        flycoTabLayout.currentTab = 2
        updateStatusBar(2)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onSwitchTab(event: IndexEvent) {
        flycoTabLayout.currentTab = event.index
        updateStatusBar(event.index)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onPlayVideoEvent(ev: PlayAdVideoEvent) {

        ttAdNative.loadRewardVideoAd(adVideoSlot, object : RewardVideoAdListenerAdapter() {

            override fun onRewardVideoAdLoad(p0: TTRewardVideoAd?) {

                p0?.setRewardAdInteractionListener(object : RewardAdInteractionListenerAdapter() {

                    var startTime: Long = 0L

                    override fun onRewardVerify(p0: Boolean, p1: Int, p2: String?) {

                    }

                    override fun onVideoComplete() {

                    }

                    override fun onAdShow() {
                        startTime = SystemClock.elapsedRealtime()
                    }

                    override fun onAdClose() {
                        entertainPresenter.postVideoClipsTime(::onShowVideoTaskDialog, ::onError)
                    }

                })

                p0?.showRewardVideoAd(this@MainActivity)
            }

            override fun onError(p0: Int, p1: String?) {
                p1?.apply {
                    Toaster.message("$this>>>$p0")
                }
            }

        })
    }


    /**
     * 广告视频看完后回调
     */
    fun onShowVideoTaskDialog(result: VideoClipTaskResult/*s: String, reward: Int, countDownTime: Int,completed:Boolean*/) {

//        AdVideoDialog.create(this, reward.toString(),msg =  s, deadline = countDownTime,completed = completed)
//                .show()

        AdVideoDialog.create(this, result).show()
    }


    override fun setStatusBarColor(colorRes: Int) {
        //全屏，同时保持状态栏
//        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
//        //不让内容顶到状态栏
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            val content = (findViewById<ViewGroup>(android.R.id.content)).getChildAt(0)
//            content?.fitsSystemWindows = true
//        }
        //设置状态栏颜色
        StatusbarUtil.setStatusBarColor(this, colorRes)
    }

    override fun onResume() {
        super.onResume()
        isVisibleNow = true
        if (changedTab != -1 && flycoTabLayout.currentTab != changedTab) {
            flycoTabLayout.currentTab = changedTab
            //reset
            changedTab = -1
        }

        if (upgradeDialog == null || (upgradeDialog?.isShowing == true))
            updatePresenter.checkUpdate()


        try {
            closeIme()
        } catch (e: Exception) {

        }
    }

    fun closeIme() {
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(window.decorView.windowToken, 0)
    }

    override fun onStop() {
        super.onStop()
        isVisibleNow = false
    }

    override fun onDestroy() {
        super.onDestroy()
        promotionDialog?.cancel()
        gamePromotionDialog?.cancel()
        EventBus.getDefault().unregister(this)
        CmGameSdk.removeGameAccountCallback()
        CmGameSdk.removeGamePlayTimeCallback()
    }


    private lateinit var updateCheck: UpdateCheck


    private var upgradeDialog: AlertDialog? = null
    override fun onUpdate(updateCheck: UpdateCheck) {
        val currentCode = BuildConfig.VERSION_CODE
        //用户已经忽略了此次更新，那么不再弹出
        if (updateCheck.version == tmpIgnoreVersion) return
        if (currentCode < updateCheck.version) {

            if (execUpdateLogic(updateCheck, false) {
                        tmpIgnoreVersion = updateCheck.version

                        if (updateCheck.forceUpdate == 1) {
                            Process.killProcess(Process.myPid())
                        }

                    }.not()) {

                if (upgradeDialog?.isShowing != false) {
                    upgradeDialog?.dismiss()
                }
                val rootView = layoutInflater.inflate(R.layout.upgrade_dialog_layout, null)

                rootView.upgrade_log.text = updateCheck.updateLog

                updateCheck.versionName?.apply {
                    rootView.upgrade_version.text = "版本$this"
                }

                upgradeDialog = AlertDialog.Builder(this)
                        .setView(rootView)
                        .setCancelable(false)
                        .create()
                rootView.upgrade_later.setOnClickListener {
                    tmpIgnoreVersion = updateCheck.version
                    if (updateCheck.forceUpdate == 1) {
                        Process.killProcess(Process.myPid())
                    } else
                        upgradeDialog?.dismiss()
                }

                rootView.upgrade_now.setOnClickListener {
                    startUpdate(updateCheck)
//                    upgradeDialog?.dismiss()
                }

                //transparent
                upgradeDialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
                upgradeDialog?.show()

            }
        }
    }

    override fun onUiComplete() {
        upgradeDialog?.dismiss()
    }

    override fun setUiProgress(progress: Int) {
        upgradeDialog?.download_progress?.isIndeterminate = false
        upgradeDialog?.download_progress?.progress = progress
    }


    private fun startUpdate(updateCheck: UpdateCheck) {
        this.updateCheck = updateCheck
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this@MainActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

                val alertDialog = AlertDialog.Builder(this@MainActivity)
                        .setTitle("申请权限")
                        .setMessage("请求SD卡读写权限，下载最新安装包")
                        .setNegativeButton("允许") { dialog, which ->
                            ActivityCompat.requestPermissions(
                                    this@MainActivity,
                                    arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE),
                                    110)
                            dialog.dismiss()
                        }
                        .setCancelable(false)
                        .create()
                alertDialog.show()

            } else {

                AlertDialog.Builder(this@MainActivity, R.style.MaterialDialogStyle)
                        .setTitle("权限不足")
                        .setMessage("没有SD卡读写权限，无法下载最新安装包，请到应用管理页面授予权限")
                        .setNegativeButton("取消") { dialog, which ->
                            ActivityCompat.requestPermissions(
                                    this@MainActivity,
                                    arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                                    110)
                            dialog.dismiss()
                        }
                        .setPositiveButton("去设置") { dialog, which ->
                            val intent = Intent()
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                            intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                            intent.data = Uri.parse("package:$packageName")
                            startActivity(intent)
                            dialog.dismiss()
                        }
                        .create()
                        .show()
            }

        } else {
            //有权限
            permitted = true
            downLoadApk(updateCheck)
        }

    }

    private fun downLoadApk(updateCheck: UpdateCheck) {
        DownLoadService.materialDialog = this
        DownLoadService.start(applicationContext, updateCheck.url, updateCheck.md5)
        upgradeDialog?.download_progress?.setVisible()
    }

    var permitted = false
    override fun onRequestPermissionsResult(requestCode: Int, @NonNull permissions: Array<String>, @NonNull grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 110) {
            for (gr in grantResults) {
                if (gr != PackageManager.PERMISSION_GRANTED)
                    return
            }
            permitted = true
            startUpdate(updateCheck)
        }
    }


    override fun gamePlayTimeCallback(gameId: String, gamePlayedTimeSeconds: Int) {
//        userPresenter.postTinyGamePlayTimeAndGetToken(gameId, gamePlayedTimeSeconds, "", ::onPlayTimeHandleIn, ::onError, ::onNewToken)
    }

    fun onPlayTimeHandleIn(msg: String?, beanReward: String?) {
        val view = layoutInflater.inflate(R.layout.play_time_dialog, null)


        val create = AlertDialog.Builder(this)
                .setView(view)
                .create()

        view.tv_reward_diamond.visibility = if (TextUtils.isEmpty(msg)) View.GONE else View.VISIBLE
        view.tv_reward_diamond.text = "+$msg"

        view.tv_reward_bean.visibility = if (TextUtils.isEmpty(beanReward)) View.GONE else View.VISIBLE
        view.tv_reward_bean.text = "+$beanReward"

        view.dialog_button.setOnClickListener {

            create.dismiss()

        }
        create.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        create.show()
    }

    class Tab(private var title: String, private var selectedIcon: Int, private var unselectedIcon: Int) : CustomTabEntity() {

        companion object G {
            fun of(t: String, s: Int, us: Int) = Tab(t, s, us)
        }

        override fun getTabUnselectedIcon(): Int {
            return unselectedIcon
        }

        override fun getTabSelectedIcon(): Int {
            return selectedIcon
        }

        override fun getTabTitle(): String {
            return title
        }

    }

    class LottieTab(
            private var path: String,
            private var title: String,
            private var selectedIcon: Int,
            private var unselectedIcon: Int
    ) : CustomTabEntity() {

        override fun getTabUnselectedIcon(): Int {
            return unselectedIcon
        }

        override fun getTabSelectedIcon(): Int {
            return selectedIcon
        }

        override fun getTabTitle(): String {
            return title
        }

        override fun extra() = path
    }


}

interface FragmentChangeListener {
    fun setStatusBarColor(colorRes: Int)
}

